<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { onMounted, ref } from 'vue';
import { fetchDeleteUser, fetchGetUserList } from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { enableStatusRecord, userGenderRecord } from '@/constants/business';
import { useTable, useTableOperate } from '@/hooks/common/table';
// import useDictionary, { useDict } from '@/hooks/common/dict';
import { useDict } from '@/hooks/common/dict';
import UserOperateDrawer from './modules/user-operate-drawer.vue';
import UserSearch from './modules/user-search.vue';
import UserDept from './modules/user-dept-tree.vue';

const appStore = useAppStore();

const sexOptions = ref<CommonType.Option[]>([]);
const sexTypes = ref<{ [key: string]: NaiveUI.ThemeColor }>({});
const sexLabels = ref<{ [key: string]: string }>({});
onMounted(async () => {
  const { getOptions: getSexOptions, getTypes, getLabels } = await useDict('sys_user_sex');
  sexOptions.value = getSexOptions();
  sexTypes.value = getTypes();
  sexLabels.value = getLabels();

  const { getOptions } = await useDict('sys_user_sex');
  sexOptions.value = getOptions();
});

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetUserList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    deptId: null,
    status: null,
    userName: null,
    sex: null,
    nickName: null,
    userPhone: null,
    userEmail: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 64
    },
    {
      key: 'userName',
      title: $t('page.manage.user.userName'),
      align: 'center',
      minWidth: 100
    },
    {
      key: 'sex',
      title: $t('page.manage.user.userGender'),
      align: 'center',
      width: 100,
      render: row => {
        if (row.sex === null) {
          return null;
        }

        // const tagMap: Record<Api.SystemManage.UserGender, NaiveUI.ThemeColor> = {
        //   1: 'primary',
        //   2: 'error'
        // };

        // const label = $t(userGenderRecord[row.sex]);

        return <NTag type={sexTypes.value[row.sex]}>{sexLabels.value[row.sex]}</NTag>;
      }
    },
    {
      key: 'nickName',
      title: $t('page.manage.user.nickName'),
      align: 'center',
      minWidth: 100
    },
    {
      key: 'userPhone',
      title: $t('page.manage.user.userPhone'),
      align: 'center',
      width: 120
    },
    {
      key: 'userEmail',
      title: $t('page.manage.user.userEmail'),
      align: 'center',
      minWidth: 200
    },
    {
      key: 'status',
      title: $t('page.manage.user.userStatus'),
      align: 'center',
      width: 100,
      render: row => {
        if (row.status === null) {
          return null;
        }

        const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
          0: 'success',
          1: 'warning'
        };

        const label = $t(enableStatusRecord[row.status]);

        return <NTag type={tagMap[row.status]}>{label}</NTag>;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small" disabled={row.id === 1}>
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

async function handleBatchDelete() {
  // request
  await fetchDeleteUser(checkedRowKeys.value);
  onBatchDeleted();
}

async function handleDelete(id: number) {
  // request
  await fetchDeleteUser(id);
  onDeleted();
}

async function edit(id: number) {
  // const dd = await useDictionary('sys_user_sex');
  // console.log(dd);
  handleEdit(id);
}
// 切换部门查询
function handleChangeDept(keys: number[]) {
  const deptId = keys[0];
  searchParams.deptId = deptId;
  getData();
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <UserSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NGrid responsive="screen" item-responsive :x-gap="12" :y-gap="8" class="sm:flex-1-hidden">
      <NGi span="0 s:0 m:4" class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
        <UserDept class="sm:flex-1-hidden card-wrapper" @change="handleChangeDept" />
      </NGi>
      <NGi span="24 s:24 m:20" class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
        <NCard
          :title="$t('page.manage.user.title')"
          :bordered="false"
          size="small"
          class="sm:flex-1-hidden card-wrapper"
        >
          <template #header-extra>
            <TableHeaderOperation
              v-model:columns="columnChecks"
              :disabled-delete="checkedRowKeys.length === 0"
              :loading="loading"
              add-auth="sys:sss"
              @add="handleAdd"
              @delete="handleBatchDelete"
              @refresh="getData"
            />
          </template>
          <NDataTable
            v-model:checked-row-keys="checkedRowKeys"
            :columns="columns"
            :data="data"
            size="small"
            :flex-height="!appStore.isMobile"
            :scroll-x="962"
            :loading="loading"
            remote
            :row-key="row => row.id"
            :pagination="mobilePagination"
            class="sm:h-full"
          />
          <UserOperateDrawer
            v-model:visible="drawerVisible"
            :operate-type="operateType"
            :row-data="editingData"
            @submitted="getDataByPage"
          />
        </NCard>
      </NGi>
    </NGrid>
  </div>
</template>

<style scoped></style>
